<script setup>
import {ref, onMounted, watch, onUnmounted} from "vue"

const props = defineProps({
  text: {
    type: String,
    default: "展开"
  },
  row: {
    type: Number,
    default: 1
  }
})

const expandRef = ref(null)
const isExpand = ref(false)
const textRef = ref(null)

let fullHeight  //展开时的高度
let lineHeight  //行高
let textHeight  //折叠后的高度

const showButton = ref(true)
function setHeights() {
  fullHeight = textRef.value.scrollHeight
  lineHeight = Number(window.getComputedStyle(expandRef.value).lineHeight.slice(0, -2))
  textHeight = lineHeight * props.row
  if(fullHeight <= textHeight){
    showButton.value = false
    textHeight = fullHeight
  }
  setTextHeight()
}

function setTextHeight(){
  expandRef.value.style.height = isExpand.value ? fullHeight + lineHeight + "px" : textHeight + "px"
}

watch(()=>isExpand.value, ()=>{
  setTextHeight()
})

onMounted(() => {
  setHeights()
})

onUnmounted(()=>{
  window.removeEventListener("resize",setHeights)
})

window.addEventListener("resize", setHeights)
</script>

<template>
  <div ref="expandRef" class="preview-container">
    <div ref="textRef">
      {{ props.text }}
    </div>
    <div class="expand-btn" @click="isExpand = !isExpand" v-if="showButton">
      {{ isExpand ? "收起" : "...展开" }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.preview-container {
  width: 100%;
  position: relative;
  overflow: hidden;
  transition: height 0.2s;
}
.expand-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  cursor: pointer;
  background: white;
  color:deepskyblue;
}
</style>